package com.tom.demo.valid.parentheses;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class ValidParentheses {
    private final static Map<Character, Character> map = new HashMap<Character, Character>() {{
        put('(', ')');
        put('[', ']');
        put('{', '}');
    }};

    public static boolean isValid(String s) {
        final Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                stack.push(c);
                continue;
            }

            for (Map.Entry<Character, Character> entry : map.entrySet()) {
                if (!entry.getValue().equals(c)) {
                    continue;
                }
                if (!stack.isEmpty() && entry.getKey().equals(stack.pop())) {
                    break;
                }
                return false;
            }
        }
        return stack.isEmpty();
    }


    /**
     * ()
     * ()[]{}
     * (]
     * ([])
     * ([)]
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(isValid("()"));
        System.out.println(isValid("()[]{}"));
        System.out.println(isValid("(]"));
        System.out.println(isValid("([])"));
        System.out.println(isValid("([)]"));
    }
}
